<?php

/**
 * This is the model class for table "{{messages}}".
 *
 * The followings are the available columns in table '{{messages}}':
 * @property integer $id
 * @property integer $from
 * @property integer $to
 * @property string $text
 * @property string $crdate
 * @property string $read
 * @property string $status_from
 * @property string $status_to
 */
class Messages extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Messages the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{messages}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('from, to, crdate', 'required'),
			array('from, to, read, status_from, status_to', 'numerical', 'integerOnly'=>true),
			array('text', 'length', 'max'=>1000),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, from, to, text, crdate, read, status_from, status_to', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'from_info'=>array(self::BELONGS_TO, 'Users', 'from'),
			'to_info'=>array(self::BELONGS_TO, 'Users', 'to'),
			'images'=>array(self::HAS_MANY, 'MessagesPhotos', 'message_id',
				'order' => 'images.id DESC',
			),	
			'musics'=>array(self::HAS_MANY, 'MessagesMusics', 'message_id',
				'order' => 'musics.id DESC',
			),	
			'videos'=>array(self::HAS_MANY, 'MessagesVideos', 'message_id',
				'order' => 'videos.id DESC',
			),				
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'from' => 'From',
			'to' => 'To',
			'text' => 'Сообщение',
			'crdate' => 'Дата создания',
			'read' => 'read',
			'status_from' => 'StatusFrom',
			'status_to' => 'StatusTo'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('from',$this->from);
		$criteria->compare('to',$this->to);
		$criteria->compare('text',$this->text,true);
		$criteria->compare('crdate',$this->crdate,true);
		$criteria->compare('read',$this->read);
		$criteria->compare('status_from',$this->status_from);
		$criteria->compare('status_to',$this->status_to);
		
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	public function getDialogs(){
		$connection=Yii::app()->db;
		$sql='SELECT t.id,
					 t.text, 
					 t.crdate, 
					 t.read,
					 `from`,
					 IF(`from` = ' . (int)Yii::app()->user->id . ', `to`, `from`) AS dialog, 
					 u.id as user_id,
					 u.full_name,
					 p.name as avatar
			    FROM (SELECT * FROM {{messages}} WHERE `from`=' . (int)Yii::app()->user->id . ' OR `to`=' . (int)Yii::app()->user->id . ' ORDER BY crdate DESC) AS t 
		   LEFT JOIN {{users}} as u
		   		  ON IF(t.`from` = ' . (int)Yii::app()->user->id . ', t.`to`, t.`from`) = u.id
		   LEFT JOIN {{photos}} as p
		   		  ON p.id = u.avatar
		   	   WHERE IF(t.`from` = ' . (int)Yii::app()->user->id . ', t.`status_from`, t.`status_to`) = 1
			GROUP BY dialog  
			ORDER BY t.crdate DESC';
		
		return $connection->createCommand($sql)->queryAll();	
	}	

	public function checkDialogs(){
		$connection=Yii::app()->db;
		$sql='SELECT * 
				FROM (SELECT * FROM  `soc_messages`
					   WHERE `from` in (SELECT `from` FROM `soc_messages` WHERE `to` = ' . (int)Yii::app()->user->id . ' AND `read` = 0 AND `status_to` = 1)
					     AND `to` = ' . (int)Yii::app()->user->id . '
					GROUP BY `from`,`to`,`read`) as t
			GROUP BY `from`,`to`
			  HAVING count(`from`) = 1';
	
		return $connection->createCommand($sql)->queryAll();
	}	

}